var Dingding = {
    params: {},
    proxy: null,
    setParams: function (params) {
        if (typeof params !== 'object') {
            return;
        }
        Dingding.params = params;
    },
    request: function () {
        var data = {
                msgtype: "markdown",
                markdown: {
                    title: Dingding.params.Subject,
                    text: Dingding.params.Subject + "\n" + Dingding.params.Message,
                },
                at: {
                    atUserIds: [Dingding.params.To],
                    isAtAll: false,
                },
            },
            response,
            url = Dingding.params.URL,
            request = new CurlHttpRequest();

        request.AddHeader('Content-Type: application/json');
        if (typeof Dingding.HTTPProxy !== 'undefined' && Dingding.HTTPProxy !== '') {
            request.SetProxy(Dingding.HTTPProxy);
        }

        if (typeof data !== 'undefined') {
            data = JSON.stringify(data);
        }
        Zabbix.Log(4, "[Dingding Webhook] message is: " + data);
        response = request.Post(url, data);

        Zabbix.Log(4, '[ Dingding Webhook ] Received response with status code ' +
            request.Status() + '\n' + response);

        if (response !== null) {
            try {
                response = JSON.parse(response);
            } catch (error) {
                Zabbix.Log(4, '[ Dingding Webhook ] Failed to parse response received from Dingding');
                response = null;
            }
        }

        if (request.Status() !== 200 || response.errcode !== 0) {
            var message = 'Request failed with status code ' + request.Status();

            if (response !== null && typeof response.errmsg !== 'undefined') {
                message += ': ' + JSON.stringify(response.errmsg);
            }

            throw message + '. Check debug log for more information.';
        }

        return response;
    },
};


try {
    var params = JSON.parse(value);

    if (typeof params.URL !== 'undefined'
        && typeof params.To !== 'undefined'
        && typeof params.Message !== 'undefined') {
        Zabbix.Log(4, '[ Dingding Webhook ] webhookURL "' + params.URL +
            '" sendto "' + params.To) + '"';
    } else {
        throw 'Missing parameter. URL, message, to parameter is required'
    }
    if (params.HTTPProxy) {
        Dingding.proxy = params.HTTPProxy;
    }
    Dingding.setParams(params);
    Dingding.request();
    return 'OK';
} catch (error) {
    Zabbix.Log(3, '[ Dingding Webhook ] ERROR: ' + error);
    throw 'Sending failed: ' + error;
}